import express from 'express';
import path from 'path';
import dotenv from 'dotenv';
import cors from 'cors';
import fs from 'fs';


dotenv.config({
  path: [
    path.resolve(process.cwd(), `.env.${process.env.NODE_ENV}`), 
    path.resolve(process.cwd(), '.env')
  ]
});

import { createpool } from "./util/db.js"
createpool();

const app = express();

app.use( express.static("public/") );
app.use(cors());

app.use(express.urlencoded({ extended: true }));
app.use(express.json());


import indexRoutes from './routes/public/index.js';
app.use(`/api/v1/index`, indexRoutes);

import adminRoutes from './routes/private/admin.js'
app.use(`/api/v1/admin`, adminRoutes);

app.use(function(req,res,next){
  res.send({
    code:404,
    msg:`${req.path} Not Found`
  })
});
app.use(function(err,req,res,next){
  let result = {
    code:500,
    msg:"服务器运行错误QAQ，请联系管理员/(ㄒoㄒ)/~~"
  }
  if(process.env.NODE_ENV=="development"){
    console.log(err);
  }else{
    let logPath = path.resolve(process.cwd(),`./logs/${new Date().getTime()}.log`);
    let info = new Date().toLocaleString() + "\n" + decodeURI(err.stack);
    fs.writeFileSync( logPath,info )
  }
  res.send(result)
});


const PORT = process.env.PORT ?? 8000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});


export default app;
